package com.eshop.eshop2021_v1.controller.before;

import com.eshop.eshop2021_v1.common.JsonResult;
import com.eshop.eshop2021_v1.pojo.Cart;
import com.eshop.eshop2021_v1.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.List;

/**
 * @author: 若若叶
 * @date: 2021/10/13 11:08 FileName: CartController Description:
 */
@Controller
@RequestMapping("/cart")
public class CartController {
  @Autowired CartService cartService;

  // 加入购物车
  @RequestMapping("/addCart")
  @ResponseBody
  public JsonResult addCart(Integer goodId, Integer goodNum, HttpSession session) {
    JsonResult result = cartService.addCart(goodId, goodNum, session);
    return result;
  }

  @GetMapping("/cartList")
  public String toCartPage(HttpSession session, Model model) {
    List<Cart> list = cartService.findCartAndGoodsInfo(session);
    BigDecimal showTotalPrice = new BigDecimal(0);
    for (Cart c : list) {
      // c 变量代表cart对象
      BigDecimal totalPrice = c.getTotalPrice();
      showTotalPrice = showTotalPrice.add(totalPrice);
    }
    model.addAttribute("cartList", list);
    model.addAttribute("TotalPrice", showTotalPrice);

    return "user/cart";
  }

  @PostMapping("/deleteOne")
  @ResponseBody
  public JsonResult deleteOne(Integer cartId) {
    return cartService.deleteOne(cartId);
  }

  @PostMapping("/deleteAll")
  @ResponseBody
  public JsonResult deleteAll(HttpSession session) {
    return cartService.deleteAll(session);
  }
}
